using System;
using System.Collections.Generic;
using System.Text;

namespace BSDS.Commands
{
    public class CommandInfo
    {
        public Dictionary<string, string> Parameters { get; private set; } 

        private CommandInfo(Dictionary<string, string> parameters)
        {
            Parameters = parameters;
        }
        
        public static CommandInfo Parse(string[] arguments)
        {
            var parameters = new Dictionary<string, string>();

            foreach (string argument in arguments)
            {
                string[] parts = argument.Split('=');

                if (parts.Length == 2)
                {
                    parameters.Add(GetParameterName(parts[0]), parts[1]);
                }
                else if (parts.Length == 1)
                {
                    parameters.Add(GetParameterName(parts[0]), null);
                }
                else
                {
                    throw new ArgumentException("Invalid argument format: " + argument);
                }
            }

            return new CommandInfo(parameters);
        }

        public static CommandInfo Parse(string command)
        {
            return Parse(command.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries));
        }

        public override string ToString()
        {
            var builder = new StringBuilder();

            foreach (var key in Parameters.Keys)
            {
                builder.Append("/").Append(key);
                
                if (Parameters[key] != null)
                {
                    builder.Append("=").Append(Parameters[key]);
                }

                builder.Append(" ");
            }

            return builder.ToString();
        }

        private static string GetParameterName(string argumentName)
        {
            if (!argumentName.StartsWith("/"))
            {
                throw new ArgumentException("Invalid parameter value: " + argumentName);
            }

            return argumentName.Substring(1, argumentName.Length - 1);
        }
    }
}